//
//  FunctionViewController.m
//  TinyFortune
//
//  Created by lc on 16/5/18.
//  Copyright © 2016年 lc. All rights reserved.
//
#import <MapKit/MapKit.h>
#import "FunctionViewController.h"
#import "LCButton.h"
#import "TalkViewController.h"
#import "AnuViewController.h"
#import "Communication.h"
#import "AVFile +  getDictionary.h"
#import "comModel.h"
#import "CLLocation+Sino.h"
#import "WishViewController.h"


@interface FunctionViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,CLLocationManagerDelegate>{
    TalkViewController *_talk;
   
    CLLocationManager *_locationManager;//定位服务器管理对象
    NSString *_lastCity;//当前城市
    NSString *_lastAddress;//省地质
    CLLocation *_currentLocation;//当前位置

}
@property (nonatomic,strong) Communication *com;
@property (weak, nonatomic) IBOutlet UIView *bgview;

- (IBAction)talkAction:(UIButton *)sender;
- (IBAction)anniversaryAction:(UIButton *)sender;
- (IBAction)wishesAction:(UIButton *)sender;
- (IBAction)shareMusicAction:(UIButton *)sender;
- (IBAction)sleepAction:(UIButton *)sender;
- (IBAction)sorryAction:(UIButton *)sender;

@end


@implementation FunctionViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewDidLoad {

    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignFirstPlayer)];
    [self.view addGestureRecognizer:tap];
    _com = [Communication new];
    _com.client = [[AVIMClient defaultClient]initWithClientId:[AVUser currentUser].mobilePhoneNumber];
  
    //创建定位服务管理器对象
    _locationManager = [CLLocationManager new];
    //定位精确度,如果设置成best就特别费电
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //距离过滤器,设置越小越耗电
    _locationManager.distanceFilter = 10 ;
    //绑定时间回调
    _locationManager.delegate = self ;

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -放弃相应事件
- (void)resignFirstPlayer{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (IBAction)talkAction:(UIButton *)sender {
    UIAlertController *talkAlert = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    //从相册中选择
    UIAlertAction *chooseAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self openPhoto];
    }];
   //将action放在controller上
    [talkAlert addAction:takePhotoAction];
    [talkAlert addAction:chooseAction];
   
    [self presentViewController:talkAlert animated:YES completion:nil];
    
    
   }
#pragma  mark -打开照相机
- (void)openCamera{
    BOOL ret = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    //判断是否支持相机
    if (ret) {
        UIImagePickerController *picker = [UIImagePickerController new];
        //设置图片资源类型
        [picker setSourceType:UIImagePickerControllerSourceTypeCamera];
        picker.delegate = self;
      
        //显示图片选择器
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"失败" message:@"科科，主人的手机不支持照相功能啊" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)openPhoto{
    UIImagePickerController *picker =[UIImagePickerController new];
    [picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    picker.delegate = self ;
    picker.allowsEditing = YES ;
    [self presentViewController:picker animated:YES completion:nil];
}
#pragma  mark - 实现选中图片协议
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = info[@"UIImagePickerControllerOriginalImage"];
    //正向传值
    _talk = [TalkViewController new];
    _talk.image = image;
    //让图片选择器消失
  
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController pushViewController:_talk animated:YES];
  
    
}
/**纪念日*/
- (IBAction)anniversaryAction:(UIButton *)sender {
    if ([[AVUser currentUser]objectForKey:@"lovers"]) {
    AnuViewController *anu = [AnuViewController new];
    [self.navigationController pushViewController:anu animated:YES];
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"您还未添加情侣,无法发送" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alertView show];
    }
}
/**心愿礼盒*/
- (IBAction)wishesAction:(UIButton *)sender {
    if ([[AVUser currentUser]objectForKey:@"lovers"]) {
    WishViewController *whish = [WishViewController new];
    [self.navigationController pushViewController:whish animated:NO];
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"您还未添加情侣,无法发送" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alertView show];
    }
}

- (IBAction)shareMusicAction:(UIButton *)sender {
     __weak typeof(self)weakSelf = self ;
   
    if ([[AVUser currentUser] objectForKey:@"lovers"]) {
    AVIMTextMessage *myMessage = [AVIMTextMessage messageWithText:[NSString stringWithFormat:@"我现在在这里 : %@ %@",_lastCity,_lastAddress ] attributes:nil];
    [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
    MBProgressHUD *hud = [MBProgressHUD HUDForView:weakSelf.view];
    hud.labelText = @"正在发送";
    //打开连接
    [_com.client openWithCallback:^(BOOL succeeded, NSError *error) {
        [_com.client createConversationWithName:@"发送位置" clientIds:@[[[AVUser currentUser] objectForKey:@"lovers"]] callback:^(AVIMConversation *conversation, NSError *error) {
            
                //当前用户发送了一条消息给恋人
                [conversation sendMessage:myMessage callback:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                      
                        [hud hide:YES];
                        //如果成功了,就把这条小心加入数据源数组，然后再刷新tableView
                        //==================获取头像========================
                        AVFile *file = [[AVUser currentUser] objectForKey:@"iconImage"];
                        NSDictionary *dict = [AVFile fileWithDictionary:file];
                        NSString *iconStr = dict[@"url"];
                        NSDictionary *tDic = @{
                                               @"iconImage":iconStr,
                                               @"text":[NSString stringWithFormat:@"我现在在这里 : %@ %@",_lastCity,   _lastAddress],
                                               @"mediaType":@"-1",
                                               @"audioUrl":@"aa",
                                               @"time":@"00",
                                               @"mes":myMessage,
                                               @"userId":myMessage.clientId
                                               };
                        comModel *model = [[comModel alloc]initWithDict:tDic];
                    
                        
                        [weakSelf.com.DBmanager insertObject:model];
                        [weakSelf.com.DBmanager insertObject:myMessage];
                        
                        
                        
                        [weakSelf.com setHidesBottomBarWhenPushed:YES];
                        [weakSelf.navigationController pushViewController:weakSelf.com animated:NO];
                        

                    }else{
                        //打印错误
                        NSLog(@"%@",error.localizedDescription);
                    }
                }];
        }];
       
    }];
    
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"您还未添加情侣,无法发送" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alertView show];
    }
}

//点击之后再聊天页面发送消息给情侣
- (IBAction)sleepAction:(UIButton *)sender {
    if ([[AVUser currentUser]objectForKey:@"lovers"]) {
        
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    MBProgressHUD *hud = [MBProgressHUD HUDForView:self.view];
    hud.labelText = @"做个好梦";
    

    NSDate *date = [NSDate new];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"MM月dd日 HH:mm:ss";
   NSString *timeString = [formatter stringFromDate:date];
   
    AVIMTextMessage *myMessage = [AVIMTextMessage messageWithText:[NSString stringWithFormat:@"%@  我睡了",timeString ] attributes:nil];
    __weak typeof(self)weakSelf = self ;
    
    
    //打开连接
    [_com.client openWithCallback:^(BOOL succeeded, NSError *error) {
            [_com.client createConversationWithName:@"我睡了" clientIds:@[[[AVUser currentUser] objectForKey:@"lovers"]] callback:^(AVIMConversation *conversation, NSError *error) {
                //当前用户发送了一条消息给恋人
                [conversation sendMessage:myMessage callback:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        [hud hide:YES];
                        
                        //如果成功了,就把这条小心加入数据源数组，然后再刷新tableView
                        //==================获取头像========================
                        AVFile *file = [[AVUser currentUser] objectForKey:@"iconImage"];
                        NSDictionary *dict = [AVFile fileWithDictionary:file];
                        NSString *iconStr = dict[@"url"];
                        NSDictionary *tDic = @{
                                               @"iconImage":iconStr,
                                               @"mes":myMessage,
                                               @"userId":myMessage.clientId,
                                               @"text":[NSString stringWithFormat:@"%@  我睡了",timeString ],
                                               @"mediaType":@"-1",
                                               @"audioUrl":@"aa",
                                               @"time":@"00"
                                               };
                        comModel *model = [[comModel alloc]initWithDict:tDic];
                       
                        //这个是数据源数组
                       // [weakSelf.com.currentUserArray
                        [weakSelf.com.DBmanager insertObject:model];
                        [weakSelf.com.DBmanager insertObject:myMessage];

                            [weakSelf.com setHidesBottomBarWhenPushed:YES];
                            [weakSelf.navigationController pushViewController:weakSelf.com animated:NO];

                    }else{
                        //打印错误
                        NSLog(@"%@",error.localizedDescription);
                    }
                }];
            
            }];
       
        }];
    
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"您还未添加情侣,无法发送" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alertView show];

    }
}

- (IBAction)sorryAction:(UIButton *)sender {
    if ([[AVUser currentUser]objectForKey:@"lovers"]) {
    [self.com setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:self
     .com animated:NO];
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"您还未添加情侣,无法发送" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alertView show];
    }
}

#pragma mark - 协议
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if (status == kCLAuthorizationStatusAuthorizedAlways) {
        //开始启用定位服务
        [_locationManager startUpdatingLocation];
    }
}


//更新坐标
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    NSLog(@"aaaaa");
    //当前坐标
    _currentLocation = [locations firstObject];
    //当前坐标转火星坐标
    // CLLocation *currentLocationMars = [currentLocation locationMarsFromEarth];
    //经纬度获取
    CLLocationCoordinate2D lastCoordinate ;
    lastCoordinate = CLLocationCoordinate2DMake(_currentLocation.coordinate.latitude, _currentLocation.coordinate.longitude);
    //地理信息获取
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:_currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //通过经纬度查询到地里信息
        if (placemarks.count > 0) { //有查询结果时候
            CLPlacemark *placemark = [placemarks objectAtIndex:0]; // 数组其实只有一个元素
            _lastCity = placemark.locality;
            _lastAddress = placemark.name;
           // self.transmitLocation(_lastCity,_lastAddress);
        }
    }];
    
    
}




@end
